﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.WebApp.KM;
using ZX.DAL.DBExtend;
using System.Data;
using System.Data.Linq;
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
using ZX.BLL.Extend;

namespace ZX.WebApp.DeskTop.Form
{
    public partial class DesktopConfigForUser : KmBasePage
    {
        private string _Action = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            _Action = QueryString("Action");
            switch (_Action)
            {
                case "LoadData":
                    LoadData();
                    break;
                case "Save":
                    Save();
                    break;
            }
        }

        protected void LoadData()
        {
            //获取模块具体栏位布局信息
            //获取模块具体栏位布局信息
            DataSet ds = new DataSet();
            string strsql = @"SELECT DISTINCT CASE WHEN sud1.AddUser IS NULL 
	                            THEN 1 
	                            ELSE (CASE WHEN sud.UserDesktopID IS NULL THEN 0 ELSE 1 END)
	                            END AS IsChecked
                                ,sdt.Region
                                ,sud.AddUser
                                        ,srd.[DeskTopTempID]
                                        ,sdt.DeskTopTempName AS [DeskTopName]
                                        ,sdt.[Height]
                                        ,MIN(ISNULL(sud.Sort,srd.[Sort])) OVER(PARTITION BY srd.[DeskTopTempID]) AS Sort
                                        ,sdt.[Src]
                                        ,sdt.PageType
                                        ,MIN(Coalesce(srd.PowerType,sdt.PowerType,0)) OVER (PARTITION  BY sdt.DeskTopTempID) AS PowerType
                                        ,sdt.[TabTools]
                                        ,sdt.More
                                FROM SysRoleDesktop srd
		                            INNER JOIN SysDesktopTemplate sdt ON srd.DeskTopTempID=sdt.DeskTopTempID
		                            INNER JOIN SysUserRole sur ON srd.RoleID=sur.RoleID
		                            LEFT JOIN SysUserDesktop sud ON srd.DeskTopTempID=sud.RoleDesktopID AND sur.UserID=sud.AddUser
		                            LEFT JOIN SysUserDesktop sud1 ON sud1.AddUser='@UserID'
                                WHERE sur.UserID='@UserID'
                                ORDER BY IsChecked desc,Sort asc";
            strsql = strsql.Replace("@UserID", this.UserId.Value.ToString());
            strsql = strsql.Replace("@UserID", this.UserId.Value.ToString());
            DbSql execsql = new DAL.DBExtend.DbSql();
            ds = execsql.Query(strsql);

            List<DeskTopModel> list = new List<DeskTopModel>();
            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    DeskTopModel m = new DeskTopModel
                    {
                        id = row["DeskTopTempID"].ToString(),
                        title=row["DeskTopName"].ToString(),
                        sort = row["Sort"].ToString(),
                        Region = row["Region"].ToString(),
                        IsChecked = row["IsChecked"].ToString(),
                        more = row["More"].ToString()
                    };
                    list.Add(m);
                }
            }
            ResponseJson(list);
        }

        protected void Save()
        {
            string leftData = QueryString("leftData");
            string rightData = QueryString("rightData");


            List<DeskTopModel> mLeft = new List<DeskTopModel>();
            if (!string.IsNullOrEmpty(leftData))
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(leftData)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(mLeft.GetType());
                    mLeft = (List<DeskTopModel>)serializer.ReadObject(ms);
                }
            }

            List<DeskTopModel> mRight = new List<DeskTopModel>();
            if (!string.IsNullOrEmpty(rightData))
            {
                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(rightData)))
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(mRight.GetType());
                    mRight = (List<DeskTopModel>)serializer.ReadObject(ms);
                }
            }

            StringBuilder sSql = new StringBuilder("");

            ////保存设置之前删除之前的配置
            sSql.Append(string.Format("delete from SysUserDesktop where AddUser='{0}' \n", this.UserId));
            string strSql1 = "insert into  SysUserDesktop values('{0}','{1}','{2}',{3},'{4}','{5}')\n";

            if (mLeft.Count > 0 || mRight.Count > 0)
            {
                foreach (var item in mLeft)
                {
                    sSql.Append(string.Format(strSql1, Guid.NewGuid(), item.id, "", item.sort, this.UserId.ToString(), DateTime.Now));
                }
                foreach (var item in mRight)
                {
                    sSql.Append(string.Format(strSql1, Guid.NewGuid(), item.id, "", item.sort, this.UserId.ToString(), DateTime.Now));
                }
            }
            BaseBussnies bll = new BaseBussnies();
            if (sSql.ToString() == "") return;
            bll.RunSqlCommand(sSql.ToString());
            ResponseJson(true);
        }
    }
}